/**
 * Copyright (c) 2013-5-9 下午5:23:29 WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.extblog.wkm.web.dao.article;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.extblog.wkm.web.dao.AbstractDao;
import org.extblog.wkm.web.util.PropertyUtil;
import org.extblog.wkm.web.vo.ArticleView;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

/**
 * @author WKM
 * Service.java history
 * 1.WKM - 2013-5-9 - Create File
 */
@Component
public class ArticleDao extends AbstractDao {

	/**
	 * 添加 body
	 * @param view
	 * @return
	 */
	public int insertArticle(ArticleView view){
		log.info("insert:" + PropertyUtil.getValue("article.insert"));
		return getTemplate().update(PropertyUtil.getValue("article.insert"),
					view.getArticleId(),
					view.getArticleName(),
					view.getArticleContent());
	}
	
	public List<Map<String, String>> selectArticle(String articleId){
		if(StringUtils.isBlank(articleId)) {
			log.info("query:" + PropertyUtil.getValue("article.select"));
			return getTemplate().query(PropertyUtil.getValue("article.select"), new Mapper());
		}
		log.info("query:" + PropertyUtil.getValue("article.select.byid"));
		return getTemplate().query(PropertyUtil.getValue("article.select.byid"), new Mapper(),articleId);
	}
	
	public int updateArticle(ArticleView view){
		log.info("update:" + PropertyUtil.getValue("article.update"));
		return getTemplate().update(PropertyUtil.getValue("article.update"),
				view.getArticleName(),
				view.getArticleContent(),
				view.getArticleId());
	}
	
	public int deleteBody(ArticleView view){
		log.info("delete:" + PropertyUtil.getValue("article.delete"));
		return getTemplate().update(PropertyUtil.getValue("article.delete"),view.getArticleId());
	}
	
	
	/**
	 * 数据单条记录使用map记录
	 * @author WKM
	 * FaceDao.java history
	 * 1.WKM - Jan 16, 2013 - Create File
	 */
	private class Mapper implements RowMapper<Map<String, String>>{

		public Map<String, String> mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			// TODO Auto-generated method stub
			Map<String, String> map = new HashMap<String, String>();
			String articleId = rs.getString("article_id");
			if(articleId != null){
				map.put("articleId", articleId);
			}
			
			String articleName = rs.getString("article_title");
			if(articleName != null){
				map.put("articleName", articleName);
			}
			
			String articleContent = rs.getString("article_content");
			if(articleContent != null){
				map.put("articleContent", articleContent);
			}
			return map;
		}
	}
}
